package org.f0rb.demo.web;

import org.f0rb.demo.common.CONSTANT;
import org.f0rb.demo.model.user.User;
import org.f0rb.demo.model.user.UserDAO;
import org.f0rb.demo.utils.RequestUtils;
import org.f0rb.demo.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.*;
import java.sql.Timestamp;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * Class ${PACKAGE_NAME} description goes here.
 *
 * @author Yuan Zhen
 * @version 1.0.0 11-12-9
 */
public class WebContextListener implements HttpSessionListener {
    private final static Logger LOGGER = LoggerFactory.getLogger(WebContextListener.class);
    AtomicInteger online = new AtomicInteger(0);
    private static UserDAO userDAO;

    private void autologin(HttpSession session) {
        User user = new User();
        user.setService("autologin");
        Cookie accountCookie = RequestUtils.getCookie(Context.getRequest(), CONSTANT.COOKIE.ACCOUNT);
        if (accountCookie == null) return;
        String account = accountCookie.getValue();
        // 用户没有设置自动登录.
        if (StringUtils.isBlank(account)) return;
        user.setAccount(account);
        // 解析cookie失败, 可能原因: 用户伪造cookie.
        if (user.username == null) return;
        // cookie里的host跟当前host不一致, 可能原因: 用户移动了cookie.
        if (!user.lasthost.equals(Context.getRequest().getRemoteHost())) return;
        User loginUser = userDAO.getByUsername(user.username);
        // 查询不到指定的User, 可能原因: cookie解析出错, 用户被删除.
        if (loginUser == null) return;

        // 这里用加密后的密码的hashcode来进行验证.
        String passcode = String.valueOf(loginUser.password.hashCode());
        if (user.password.equals(passcode)) {
            loginUser.lasthost = Context.getRequest().getRemoteAddr();
            //loginUser.online = 1;
            loginUser.lastlogin = new Timestamp(System.currentTimeMillis());
            userDAO.login(loginUser);
            Context.setLoginUser(session, loginUser.toSessionUser());
        }
    }

    private void autologout(HttpSession session) {
        User sessionUser = Context.getLoginUser(session);
        if (sessionUser != null) {
            userDAO.logout(sessionUser.id);
        }
    }

    /**
     * 自动登录处理.
     *
     * @param se HttpSessionEvent
     */
    @SuppressWarnings("unchecked")
    public void sessionCreated(HttpSessionEvent se) {
        if (userDAO == null) {
            WebApplicationContext wac = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(se.getSession().getServletContext());
            userDAO = (UserDAO) wac.getBean("userDAO");
        }
        autologin(se.getSession());
        //"<li class=\"l_2\"><div id=\"ca_{0}\"><span id=\"ca_{0}_text\" class=\"t_1\">{1}</span><span class=\"t_2\"><input class=\"no_border\" type=\"checkbox\" id=\"T_2_{0}\" name=\"T_2_{0}\" value=\"2_{0}\" {3}><input type=\"hidden\" value=\"T_2_{0}\" name=\"T_agent\"></span><span class=\"t_2\"><input class=\"no_border\" type=\"checkbox\" id=\"E_2_{0}\" name=\"E_2_{0}\" value=\"2_{0}\" {4}><input type=\"hidden\" value=\"E_2_{0}\" name=\"E_agent\"></span><span class=\"t_1\"><a href=\"javascript:agent.edit({0});\">Edit</a> | <a href=\"javascript:agent.del({0})\">X</a></span><div class=\"clear\"></div><div><span id=\"keywords_{0}_text\" class=\"t_1\">{2}</span></div></div><div id=\"ca_{0}_edit\" style=\"display: none\"><label class=\"t_1\"><input id=\"ca_{0}_input\" type=\"text\" name=\"agent_name\" value=\"{1}\"></label><label class=\"t_3\"><input id=\"keywords_{0}_input\" type=\"text\" name=\"keywords\" value='{2}' style=\"width: 100%\"></label><span class=\"t_1\"><a href=\"javascript:agent.update({0});\">SAVE</a> | <a href=\"javascript:agent.cancel({0})\">CANCEL</a></span></div><div class=\"clear\"></div></li>";
        LOGGER.info("当前在线 {} 人", online.incrementAndGet());
    }

    /** Session is destroyed. */
    public void sessionDestroyed(HttpSessionEvent se) {
        autologout(se.getSession());
        LOGGER.info("当前在线 {} 人", online.decrementAndGet());
    }
}
